import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import type { User } from './user'
import { authApi } from '@/api/auth'

export interface LoginCredentials {
  username: string
  password: string
}

export interface RegisterData {
  username: string
  email: string
  password: string
  confirmPassword: string
}

export interface AuthResponse {
  user: User
  token: string
  message?: string
}

export const useAuthStore = defineStore('auth', () => {
  const userStore = useUserStore()

  // 状态
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const isLoggedIn = computed(() => userStore.isAuthenticated)

  // 清除错误信息
  const clearError = () => {
    error.value = null
  }

  // 登录
  const login = async (credentials: LoginCredentials): Promise<boolean> => {
    try {
      isLoading.value = true
      clearError()

      // 这里调用实际的登录API
      const { code, data } = (await authApi.login(credentials)) as {
        code: number
        data: AuthResponse
      }
      // console.log(code, data, 'response--登录')
      if (code == 200) {
        userStore.setUser(data.user, data.token)
        return true
      }
      return false
    } catch (err) {
      error.value = err instanceof Error ? err.message : '登录失败'
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  const register = async (data: RegisterData): Promise<boolean> => {
    try {
      isLoading.value = true
      clearError()

      // 验证密码
      if (data.password !== data.confirmPassword) {
        error.value = '两次输入的密码不一致'
        return false
      }

      // 这里调用实际的注册API
      const response = await authApi.register(data)
      // console.log(resCode, resData, 'response--注册')
      if (response.code == 200) return true
      return false
    } catch (err) {
      error.value = err instanceof Error ? err.message : '注册失败'
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = () => {
    userStore.logout()
    clearError()
  }

  // 检查认证状态（开发环境下：后端不可用时不强制登出）
  const checkAuth = async (): Promise<boolean> => {
    if (!userStore.token) {
      return false
    }

    if (!userStore.isTokenValid()) {
      userStore.logout()
      return false
    }

    try {
      // 后端校验 token 有效性
      const resp = await authApi.validateToken(userStore.token)
      // console.log(resp, 'resp--检查认证状态')
      // 拦截器已保证 code===200，这里只看 data 布尔值
      return !!resp.data
    } catch {
      // 后端未启动/接口不存在/网络异常：
      // 开发环境放行，生产环境严格返回 false
      const allowInDev = (import.meta as unknown as { env?: { DEV?: boolean } }).env?.DEV === true
      return allowInDev ? true : false
    }
  }

  // 自动登录（从本地存储恢复）
  const autoLogin = async (): Promise<boolean> => {
    try {
      // 从本地存储初始化
      userStore.initializeFromStorage()
      // console.log(userStore.user, 'userStore.user--自动登录')
      // 检查认证状态
      return await checkAuth()
    } catch (err) {
      console.error('Auto login failed:', err)
      userStore.logout()
      return false
    }
  }

  return {
    // 状态
    isLoading,
    error,
    isLoggedIn,

    // 方法
    login,
    register,
    logout,
    checkAuth,
    autoLogin,
    clearError,
  }
})
